package com.psjj.privilege.web.servlet;

import com.psjj.privilege.po.Role;
import com.psjj.privilege.po.User;
import com.psjj.privilege.service.RoleService;
import com.psjj.privilege.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/user.do")
public class UserController extends BasicServlet {
    private static final String BASIC_URL = "/WEB-INF/page/user/";
    private UserService userService = new UserService();
    private RoleService roleService = new RoleService();
    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得提交参数
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        //判断登录是否成功
        //User user = userService.login(username,pwd);
        //User user = userService.loginJoinRoles(username,pwd);
        //判断登录是否成功，并关联角色信息，角色关联权限信息
        User user = userService.loginJoinRolesJoinPrivileges(username,pwd);
        /*if(user!=null){
            //登录成功将用户信息存入session
            req.getSession().setAttribute("user",user);
            //重定向到后台主页
            resp.sendRedirect(req.getContextPath()+"/main.do?method=mainUI");
        } else {
            //登录失败
            req.setAttribute("error","用户名或者密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }*/
        if(user!=null){
            if(user.getStatus()==1){
                user.setUrls((List<String>) req.getServletContext().getAttribute("urls"));
                //登录成功将用户信息存入session
                req.getSession().setAttribute("user",user);
                //重定向到后台主页
                resp.sendRedirect(req.getContextPath()+"/main.do?method=mainUI");
            }else {
                //登录失败
                req.setAttribute("error","用户已禁用，请联系管理员！！！");
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }
        } else {
            //登录失败
            req.setAttribute("error","用户名或者密码错误");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }
    //安全退出
    private void exit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //session失效
        req.getSession().invalidate();
        //重定向到登录页面
        resp.sendRedirect(req.getContextPath()+"/login.jsp");
    }
    //用户列表
    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得用户名
        String username = req.getParameter("username");
        if(username == null || "".equals(username) || "null".equals(username)){
            username = "%%";
        }else {
            username = "%"+username+"%";
        }
        //获得当前页
        int currentPage = req.getParameter("currentPage")==null?1:
                Integer.parseInt(req.getParameter("currentPage"));
        if(currentPage<1){
            currentPage=1;
        }
        //设置每页显示的数据大小
        int pageSize = 10;
        //查询数据库的记录数
        int total = userService.getCount(username);
        //计算总页数
        int pageNum = (int)Math.ceil(total/(double)pageSize);
        if(currentPage>pageNum){
            currentPage = pageNum;
        }
        //计算当前页数据
        int begin = (currentPage-1)*10;  // 第一页 0 ,10(9)   第二页 10 ,10(19) 第三页 20,10(29)
        List<User> list = userService.getPage(username,begin,pageSize);
        //存数据
        req.setAttribute("currentPage",currentPage);
        req.setAttribute("pageSize",pageSize);
        req.setAttribute("pageNum",pageNum);
        req.setAttribute("total",total);
        req.setAttribute("list",list);
        //转发到查询页面
        req.getRequestDispatcher(BASIC_URL+"table.jsp").forward(req,resp);
    }
    //跳转至添加页面
    private void addUI(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //查询所有角色信息
        List<Role> roles = roleService.queryRoles();
        //将所有角色信息存入req域中
        req.setAttribute("roles",roles);
        //将所有角色信息转发至用户添加页面
        req.getRequestDispatcher(BASIC_URL+"add.jsp").forward(req,resp);
    }
    //添加用户数据
    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取表单数据
        String username = req.getParameter("username");
        String[] rids = req.getParameterValues("rid");
        String phone = req.getParameter("phone");
        String pwd = req.getParameter("pwd");
        //将数据封装到user对象中
        User user = new User();
        user.setUsername(username);
        user.setPhone(phone);
        user.setPwd(pwd);
        //将user数据添加到数据库中并维护角色信息
        userService.addUserJoinRoles(user,rids);
        //重定向到查询页面
        resp.sendRedirect(req.getContextPath()+"/user.do?method=list");
    }
    //跳转至修改页面
    private void editUI(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得提交参数用户id
        int uid = Integer.parseInt(req.getParameter("uid"));
        //获得用户信息
        User user = userService.queryUserByUid(uid);
        //获得所有角色信息,并关联当前用户的所拥有的角色状态
        List<Role> roles = roleService.queryRolesJoinRoleStatus(uid);
        req.setAttribute("user",user);
        req.setAttribute("roles",roles);
        //转发到修改页面
        req.getRequestDispatcher(BASIC_URL+"update.jsp").forward(req,resp);
    }
    //修改数据
    private void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得表单数据
        int uid = Integer.parseInt(req.getParameter("uid"));
        String username = req.getParameter("username");
        String phone = req.getParameter("phone");
        String[] rids = req.getParameterValues("rid");
        User user = new User();
        user.setUid(uid);
        user.setUsername(username);
        user.setPhone(phone);
        //修改用户数据，并重新关联角色信息
        userService.editUserJoinRole(user,rids);
        //重定向到查询页面
        resp.sendRedirect(req.getContextPath()+"/user.do?method=list");
    }
    //删除用户
    private void del(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得表单数据
        int uid = Integer.parseInt(req.getParameter("uid"));
        //根据删除用户信息
        userService.del(uid);
        //重定向到查询页面
        resp.sendRedirect(req.getContextPath()+"/user.do?method=list");
    }
    //重置密码
    private void resetPwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获得表单数据
        int uid = Integer.parseInt(req.getParameter("uid"));
        //重置密码
        userService.resetPwd(uid);
        req.getSession().invalidate();
        //重定向到登录页面
        resp.getWriter().println("<script>parent.location.href='"+req.getContextPath()+"/login.jsp';</script>");
    }
}
